// pages/demand/demand.js
var header = getApp().globalData.header; //获取app.js中的请求头
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,//导航栏高度
    openid:null,
    typeIndex:0,//需求类型下标
    isHaveLogin: 'false',
    index: null,
    imgList: [],
    cardCur: 0,
    userInfo:{},
    swiperList: [{
      id: 0,
      type: 'image',
      url: 'https://www.yujiancs.cn/images/lunbo7.png'
    },{
        id: 1,
        type: 'image',
        url: 'https://www.yujiancs.cn/images/lunbo8.png'
      } ,{
        id: 2,
        type: 'image',
        url: 'https://www.yujiancs.cn/images/lunbo5.jpg'
      }
  ],
    //悬赏金额
    checkbox: [{
      value: 0,
      name: '1元',
      money: 1,
      checked: true,
      hot: true,
    }, {
      value: 1,
      name: '2元',
      money: 2,
      checked: false,
      hot: true,
    }, {
      value: 2,
      name: '3元',
      money: 3,
      checked: false,
      hot: true,
    }, {
      value: 3,
      name: '5元',
      money: 5,
      checked: false,
      hot: true,
    }, {
      value: 4,
      name: '10元',
      money: 10,
      checked: false,
      hot: false,
    }, {
      value: 5,
      name: '20元',
      money: 20,
      checked: false,
      hot: false,
    }],
    //选择的悬赏金
    bounty: 1,
    //需求分类
    picker: [],

  }, 
  //改变需求类型
  PickerChange(e) {
    console.log(e);
    this.setData({
      typeIndex: e.detail.value
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    var that = this;
    var number = 0;
    for (var i = 0; i < that.data.checkbox.length; i++) {
      if (that.data.checkbox[i].checked) {
        //记录次数
        number++,
          this.setData({
            bounty: that.data.checkbox[i].money,
          })
      }

    }

    //如果一个都没有选中，则默认为0
    if (number == 0) {
      this.setData({
        bounty: 0
      })
    }
    this.setData({
      modalName: null
    })
  },
  //赏金金额选择
  ChooseCheckbox(e) {
    let items = this.data.checkbox;
    console.log(e)
    let values = e.currentTarget.dataset.value;
    for (let i = 0; i < items.length; ++i) {

      if (items[i].value == values) {
        items[i].checked = !items[i].checked;
      } else {
        items[i].checked = false;
      }

    }
    this.setData({
      checkbox: items
    })
  },
  //选择上传图片开始
  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  //保存图片路径
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  //弹出消息提示框
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除这这张图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  //选择上传图片结束
  /**
   * 判断是否已经登录
   */
  IsLogin() {
    var that=this;
    if (app.globalData.userInfo==null) {
      wx.showModal({
        title: "未登录",
        content: "您当前还未登录，是否前往登录？",
        success: function (res) {
            wx.switchTab({
              url: '/pages/me/me',
            })
        }
      })
    }
    return true;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getStorages();
    this.IsLogin();
    //请求，初始化收货地址
    

  },
  InitData(){
    var that=this;
    //请求需求类型
    wx.request({
      url: 'https://www.yujiancs.cn/OrderType/List',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        for (let index = 0; index < res.data.item.length; index++) {
          that.setData({
            picker:that.data.picker.concat(res.data.item[index].Name)
          })
        }
      }
    })
    if(app.globalData.openId!=null){
      wx.request({
        url: 'https://www.yujiancs.cn/UserInfo/SelectUser', //仅为示例，并非真实的接口地址
        data: {
         wxid:app.globalData.openId
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success (res) {
          console.log(res.data)
          var userinfo={Address:res.data[0].Address,Id:res.data[0].Id}
          that.setData({
            userInfo:userinfo
          })
        }
      })
      
    }else{
      that.IsLogin();
    }
  },
  //获取缓存
  getStorages() {
    var that = this;
    wx.getStorage({
      key: 'OpenId',
      success (res) {
        console.log(res.data)
       app.globalData.openId=res.data
       //执行初始化数据
       that.InitData();
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  formSubmit(e) {
    if(app.globalData.userInfo==null){
     this.IsLogin();
     return;
    }
    //非空验证
    if(e.detail.value.Title==""){
      wx.showToast({
        title: '标题不能为空！',
        icon:"none"
      })
      return;
    }
     if(e.detail.value.Address==""){
      wx.showToast({
        title: '地址不能为空！',
        icon:"none"
      })
      return;
    }
    wx.showToast({
      title: '提交中',
      icon: 'loading',
    })
    var that = this
    console.log(e)
          //调用上传数据
          wx.request({
            url: 'https://www.yujiancs.cn/Orders/AddInfo', //仅为示例，并非真实的接口地址
            data: {
              Title: e.detail.value.Title,
              Money: e.detail.value.Money,
              Remarks: e.detail.value.Remarks,
              Address: e.detail.value.Address,
              WeixinID: that.data.openid,
              ImgName:""+that.data.imgList,
              UserID :that.data.userInfo.Id,
              Synopsis:e.detail.value.Synopsis,
              state:"0",
              OrderTypeId:that.data.typeIndex+1
            },
            method:"POST",
            header: {
              'content-type': 'application/json' // 默认值
            },
            success (res) {
              console.log(res.data)
              if(res.data.state){
                  wx.navigateTo({
                    url: '/pages/submitSuccess/submitSuccess',
                  })
              }
            }
          })
    //调用上传图片方法
    that.uploadImage();
  },

  //循环上传图片方法
  uploadImage() {
    var that = this;
    var number=0;
    for (var j = 0; j < that.data.imgList.length; j++) {
      var ind = j;
      //上传图片
      wx.uploadFile({
        url: 'https://www.yujiancs.cn/Api/imagesUpload', //仅为示例，非真实的接口地址
        filePath: that.data.imgList[ind],
        name: 'file',
        formData: {
        },
        success: function (res) {
          console.log(res)
          if(res.errMsg=="uploadFile:ok"){
            console.log("上传成功")
          }
        }
      })
    }
   
  }

})